package com.dove.ohpm.service

import com.dove.ohpm.model.LocalResponse
import com.dove.ohpm.model.Package
import com.dove.ohpm.model.Response
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit

class NetClient {
    private var total = 0
    private val packages: MutableList<Package> = mutableListOf()

    companion object {
        private var customHostUrl = ""
        fun setCustomHostUrl(schema: String, host: String, port: Int) {
            customHostUrl = if (port > 0) "${schema}://${host}:${port}" else ""
        }
    }

    fun search(customHost: Boolean, keywords: String, page: Int): List<Package> {
        if (total in 1..page && page != 1)
            return listOf()
        val condition = URLEncoder.encode(keywords, StandardCharsets.UTF_8)
        val link =
            if (customHost) "${customHostUrl}/api/packages/search?name=${condition}&currentPage=${page}&pageSize=10" else "https://ohpm.openharmony.cn/ohpmweb/registry/oh-package/openapi/v1/search?condition=${condition}&pageNum=${page}&pageSize=10&sortedType=relevancy&isHomePage=false"
        val client = OkHttpClient().newBuilder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS).callTimeout(5, TimeUnit.SECONDS).build()
        val request: Request = Request.Builder()
            .url(link)
            .addHeader("Origin", "https://ohpm.openharmony.cn")
            .addHeader("Referer", "https://ohpm.openharmony.cn")
            .build()
        val content = client.newCall(request).execute().body()?.string()
        try {
            if (!content.isNullOrEmpty()) {
                val json = Json { ignoreUnknownKeys = true }
                val array: List<Package>
                if (!customHost) {
                    val jsonElement = json.decodeFromString<Response>(content)
                    if (page == 1) {
                        total = jsonElement.body.pages
                        packages.clear()
                    }
                    array = jsonElement.body.rows
                } else {
                    val jsonElement = json.decodeFromString<LocalResponse>(content)
                    if (page == 1) {
                        total = jsonElement.data.total
                        packages.clear()
                    }
                    array = jsonElement.data.data
                }
                packages.addAll(array)
                return array
            }
        } catch (ex: Exception) {
            Messages.showErrorDialog(null as Project?, ex.message, "Error")
        }
        return listOf()
    }
}